<!-- 提货单模板 -->
<template>
  <el-dialog
    v-model="visibility"
    title="选择模版"
    width="65%"
    draggable
    :close-on-click-modal="false">
    <div class="lading_bill_template">
      <el-card
        v-permission="validateButtonPermission(route, 1)"
        class="search_card h5Card"
        ref="searchCardRef">
        <el-form
          :model="formData"
          class="search_form">
          <el-row>
            <el-form-item label="模板名称">
              <el-input
                v-model="formData.fullName"
                style="width: 100%"
                placeholder="模板名称"
                clearable>
                <template #prefix>
                  <el-icon>
                    <search />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-row>
          <el-dialog
            title="文件序号"
            v-model="dialogVisible"
            draggable
            append-to-body="false"
            @close="clearInfo"
          >
            <el-row>
              <el-form-item label="文件序号">
                <el-input
                  v-model="formData.fileNumber"
                  style="width: 200px"
                  placeholder="请输入文件序号"
                  clearable>
                  <template #prefix>
                    <el-icon>
                      <search />
                    </el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </el-row>
            <template #footer>
              <div class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="dialogConfirm">
                  确认
                </el-button>
              </div>
            </template>
          </el-dialog>
        </el-form>
        <div class="top-btn">
          <div></div>
          <div>
            <el-button
              type="primary"
              @click="getList(formData)"
              class="search">
              <template #icon>
                <el-icon>
                  <search />
                </el-icon>
              </template>
              {{ config.button.text.query }}
            </el-button>
            <el-button @click="reset">
              <template #icon>
                <el-icon>
                  <Refresh />
                </el-icon>
              </template>
              {{ config.button.text.reset }}
            </el-button>
          </div>
        </div>
      </el-card>
      <div :style="{ height: tableHeight,overflow: 'auto'}">
        <el-card
          class="table_card info-card"
          v-for="item in tableData"
          :key="item.id"
          @click="openDialog(item)">
          <div class="info-item">
            <div class="info-title">模板名称：</div>
            <div class="info-main">{{ item.fullName }}</div>
          </div>
          <div class="info-item">
            <div class="info-title">已选配置：</div>
            <div class="info-main">
              <div
                v-for="item in JSON.parse(item.templateConfig).title"
                :key="item"
                class="tag">
                <el-tag v-if="item === 'DELIVERY_DATE'">提货时间</el-tag>
                <el-tag v-if="item === 'PRODUCT_NAME'">品名</el-tag>
                <el-tag v-if="item === 'PACKAGING'">包装</el-tag>
                <el-tag v-if="item === 'SPECIFICATION'">规格</el-tag>
                <el-tag v-if="item === 'QUANTITY'">数量（袋）</el-tag>
                <el-tag v-if="item === 'WEIGHT'">重量（吨）</el-tag>
                <el-tag v-if="item === 'SUPPLIER'">供货单位</el-tag>
                <el-tag v-if="item === 'MANUFACTURER'">厂家</el-tag>
                <el-tag v-if="item === 'PAID_UNIT_PRICE'">已付单价（元）</el-tag>
                <el-tag v-if="item === 'PURCHASE_UNIT_PRICE'">采购单价（元）</el-tag>
                <el-tag v-if="item === 'WAREHOUSING_FEE'">仓储费</el-tag>
                <el-tag v-if="item === 'PURCHASE_TOTAL_PRICE'">采购总价（元）</el-tag>
                <el-tag v-if="item === 'DEDUCT_DEPOSIT'">已抵扣保证金</el-tag>
                <el-tag v-if="item === 'ACTUAL_PAYMENT'">实际应付款</el-tag>
                <el-tag v-if="item === 'DRIVER_INFO'">司机信息</el-tag>
                <el-tag v-if="item === 'TRIP'">车次</el-tag>
              </div>
            </div>
          </div>
        </el-card>
      </div>
    </div>
    <template #footer>
      <div>
        <el-button @click="visibility = false">{{ config.button.text.close }}</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from "vue";
import config from "@/common/element-plus/config";
import ApiDeliveryTemplate from "@/api/modules/delivery-template"
import message from "@/common/element-plus/message";
import { useTable } from "@/hooks/useTable"
import Pagination from "@/components/Pagination.vue"
import Table from "@/components/Table.vue"
import { validateButtonPermission } from "@/common/utils/validate";
import { useRoute } from "vue-router"
// import Edit from "./component/Edit.vue"
// import Preview from "./component/Preview.vue"
import { useAppStore } from "@/stores/app"
import { storeToRefs } from "pinia";
import app from "@/common/config/app";
import { ElMessageBox } from "element-plus";
import axios from "axios";

const route = useRoute()
// 查询表单
const formData = ref({})
// 新增修改组件实例
const editRef = ref()
// 预览组件实例
const previewRef = ref()
// 表格每行数据
const rowData = ref({})
// 表格高度(固定表头)
const height = ref(0)
// 固定数据
const list = ref([]);
// 查询卡片实例
const searchCardRef = ref()
// 弹窗
const visibility = ref(false)
//文件序列弹窗
const dialogVisible = ref(false)
const token = localStorage.getItem(localStorage.getItem("tokenName"))
const headers = ref({});
if (token) {
  headers.value["yg-token"] = token;
}

const clearInfo = () => {
  formData.value.fileNumber=''
}

// hooks
const { tableMethods, tableState, pagination } = useTable({
  fetchDataApi: async (data) => {
    const { pageSize, pageNum } = pagination
    const res = await ApiDeliveryTemplate.selectPage(data, {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
    })
    return {
      list: res.data.records,
      total: res.data.total
    }
  }
})
const { getList } = tableMethods
const { pageSize, pageNum } = pagination
const { total, tableLoading, tableData } = tableState
const props = defineProps(["selectIds"])


const selectRow = ref();
//打开文件序列弹窗
const openDialog = (info) => {
  dialogVisible.value = true;
  selectRow.value = info;
}

//弹窗确认
const dialogConfirm = () => {
  selectEvent(selectRow.value);
}

// 选择
const selectEvent = (row) => {
  ElMessageBox.confirm("确定要生成提货单吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const params = {
      id: row.id,
      trainPickRecordIds: props.selectIds,
      fileNumber:formData.value.fileNumber
    }

    try {
      const response = await axios.post(`${import.meta.env.VITE_API}/deliveryTemplate/generateDeliveryOrder`, params, {
        responseType: "blob", // 指定响应类型为 Blob
        headers: {
          "yg-token": token  // 根据后端要求设置 Token 头部
        }
      });
      const contentDisposition = response.headers["content-disposition"];
      let fileName = "文件.xlsx";
      if (contentDisposition && contentDisposition.includes("filename=")) {
        fileName = contentDisposition
          .split("filename=")[1]
          .split(";")[0]
          .replace(/['"]/g, "");
        fileName = decodeURIComponent(fileName)
      }

      const blob = new Blob([response.data], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      });

      const link = document.createElement("a");
      link.href = URL.createObjectURL(blob);
      link.download = fileName;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(link.href);
      dialogVisible.value=false;
    } catch (error) {
      message.error(`下载失败:${error.message}`);
    }

    visibility.value = false;
  }).catch(() => {
    // 用户点击了取消按钮
  });
}

// 重置
const reset = () => {
  formData.value = {}
  getList()
}

defineExpose({ visibility })

watch(() => visibility.value, async (newVal) => {
  if (newVal) {
    const data = await ApiDeliveryTemplate.getTemplateTitle()
    list.value = data.data
    // resizeObserver.observe(searchCardRef.value.$el)
  }
}, { immediate: true })
</script>

<style lang="scss" scoped>
.lading_bill_template {
  .search_card {
    margin-bottom: 4px;

    :deep(.el-card__body) {
      padding: 10px;
      // display: flex;
      justify-content: space-between;
    }

    .el-button {
      margin: 5px 10px 5px 0;
    }

    .el-form-item {
      margin-right: 10px;
      padding: 5px 0;
    }

    .top-btn{
      margin-top: 5px;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
  }

  .expanded{
    margin-right: 10px;
    text-align: right;
    color:#e6a23c;

    span{
      font-size: 14px;
    }
  }

  .table_card {
    :deep(.el-card__body) {
      padding: 0;
    }
  }

  .info-card {
    padding: 10px;
    margin-bottom: 3px;
    .info-item {
      display: flex;
      padding: 5px 0;
      .info-title{
        width: 80px;
        color: #999;
      }
      .info-main{
        flex: 1;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }
  }
}

.top-btn{
  text-align: right;
  color: #409eff;

  .top-btn-item{
    // display: flex;
    // align-items: center;
    margin-right: 5px;
  }
}

.el-form-item{
  width: 100%;
}
</style>